package com.bdth.bdthiss.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.bdth.bdthiss.entity.*;
import com.bdth.bdthiss.service.*;
import com.bdth.bdthiss.util.DateUtil;
import com.bdth.bdthiss.util.ExcelUtils;
import com.bdth.bdthiss.util.StringUtil;
import com.bdth.bdthiss.vo.*;
import com.google.common.io.ByteStreams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 合同信息 前端控制器
 * </p>
 *
 * @author LGP
 * @since 2019-08-26
 */
@Controller
@RequestMapping("/contract")
public class ContractController {

    @Autowired
    private ContractService contractService;

    @Autowired
    private UseropService useropService;

    @Autowired
    private SendmkService sendmkService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private UserService userService;

    @Autowired
    private ContractProductService contractProductService;

    @Autowired
    private BillsService billsService;

    @Autowired
    private BdcardService bdcardService;

    @Autowired
    private UserContractService userContractService;

    @RequestMapping("index")
    public String index(){
        return "contract/index";
    }

    @RequestMapping("cwindex")
    public String cwindex(){
        return "contract/cwindex";
    }

    @RequestMapping("newindex")
    public String newindex(){
        return "contract/newindex";
    }

    @RequestMapping("delindex")
    public String delindex(){
        return "contract/delindex";
    }

    @RequestMapping("concern")
    public String concern(){
        return "contract/concern";
    }

    @RequestMapping("easyform")
    public String easyform(){
        return "contract/easyform";
    }

    @RequestMapping("form")
    public String form(ModelMap map, @RequestParam int id){
        Contract bean = contractService.selectById(id);
        map.addAttribute("details",bean.getDetails());
        return "contract/form";
    }

    @RequestMapping("newform")
    public String newform(){
        return "contract/newform";
    }

    @RequestMapping("editform")
    public String editform(ModelMap map, @RequestParam int id){
        Contract bean = contractService.selectById(id);
        ContractVo result = new ContractVo();
        BeanUtils.copyProperties(bean,result);
        if(bean.getServiceDate()!=null && !bean.getServiceDate().equals(""))
            result.setServiceDateValue(DateUtil.format(bean.getServiceDate(),"yyyy-MM-dd"));
        if(bean.getCrtime()!=null && !bean.getCrtime().equals(""))
            result.setCrtimeValue(DateUtil.format(bean.getCrtime(),"yyyy-MM-dd"));
        if(bean.getLastpaytime()!=null && !bean.getLastpaytime().equals(""))
            result.setLastpaytimeValue(DateUtil.format(bean.getLastpaytime(),"yyyy-MM-dd"));

        map.addAttribute("bean",result);
        return "contract/editform";
    }

    @RequestMapping(value = "search")
    public String search(){
        return "contract/search";
    }

    @RequestMapping(value = "delsearch")
    public String delsearch(){
        return "contract/delsearch";
    }

    @RequestMapping(value = "file")
    public String file(){
        return "contract/file";
    }

    @RequestMapping(value = "sendmk")
    public String sendmk(){
        return "contract/sendmk";
    }

    @RequestMapping(value = "payment")
    public String payment(){
        return "contract/payment";
    }

    @RequestMapping(value = "customer")
    public String customer(){
        return "contract/customer";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public PageVo<Contract> getPageList(HttpServletRequest request, Pagination<Contract> pagination,
                                        @RequestParam(required = false) String code,
                                        @RequestParam(required = false) String name,
                                        @RequestParam(required = false) String type,
                                        @RequestParam(required = false) String total,
                                        @RequestParam(required = false) String status,
                                        @RequestParam(required = false) String crtime,
                                        @RequestParam(required = false) String introtype,
                                        @RequestParam(required = false) String signmanid,
                                        @RequestParam(required = true) String del){
        Map<String ,Object> query = new HashMap<>();
        //查询条件
        if(name!=null && !name.equals(""))
            query.put("name",name);
        if(code!=null && !code.equals(""))
            query.put("code",code);
        if(type!=null && !type.equals(""))
            query.put("type",type);
        if(total!=null && !total.equals(""))
            query.put("total",total);
        if(status!=null && !status.equals(""))
            query.put("status",status);
        if(crtime!=null && !crtime.equals(""))
            query.put("crtime",crtime);
        if(introtype!=null && !introtype.equals(""))
            query.put("introtype",introtype);
        if(signmanid!=null && !signmanid.equals(""))
            query.put("signmanid",signmanid);
        User session = (User)request.getSession().getAttribute("loginUser");
        if(session!=null && session.getGroupid()!=0){
            String groups = session.getGroups();
            if(groups.equals("保密人员")){
                Integer departid = session.getDepartid();
                EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
                userEntityWrapper.eq("departid",departid);
                List<User> ls = userService.selectList(userEntityWrapper);
                String sign="";
                for(User u:ls){
                    sign+= u.getId()+",";
                }
                sign += "0";
                query.put("signmanid",sign);
            }
            if(groups.equals("财务人员")){
                Integer departid = session.getDepartid();
                EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
                userEntityWrapper.eq("departid",departid);
                List<User> ls = userService.selectList(userEntityWrapper);
                String sign="";
                for(User u:ls){
                    sign+= u.getId()+",";
                }
                sign += "0";
                query.put("signmanid",sign);
            }
            if(groups.equals("销售人员")){
                //只能看到自己的合同
                query.put("signmanid",session.getId());
            }
            if(groups.equals("审核人员")){
                Integer departid = session.getDepartid();
                EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
                userEntityWrapper.eq("departid",departid);
                List<User> ls = userService.selectList(userEntityWrapper);
                String sign="";
                for(User u:ls){
                    sign+= u.getId()+",";
                }
                sign += "0";
                query.put("signmanid",sign);
            }
        }
        query.put("del",del);
        Page<Contract> items = contractService.listPages(pagination, query);
        PageVo<Contract> pageVo = new PageVo<>(items.getRecords(),items.getTotal());
        return pageVo;
    }

    /**
     *用户关注的合同
     */
    @RequestMapping(value = "concernList")
    @ResponseBody
    public PageVo<Contract> getPageList(HttpServletRequest request, Pagination<Contract> pagination){
        User session = (User)request.getSession().getAttribute("loginUser");
        EntityWrapper<UserContract> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("userid",session.getId());
        List<UserContract> userContractList = userContractService.selectList(entityWrapper);
        String contractIds = "";
        for(UserContract bean : userContractList){
            contractIds+=bean.getContractid()+",";
        }
        contractIds += "0";
        Map<String ,Object> query = new HashMap<>();
        query.put("contractIds",contractIds);
        Page<Contract> items = contractService.listPages(pagination, query);
        PageVo<Contract> pageVo = new PageVo<>(items.getRecords(),items.getTotal());
        return pageVo;
    }

    @RequestMapping(value = "itemList")
    @ResponseBody
    public PageVo<ContractProduct> itemList(Pagination<Contract> pagination,@RequestParam(required = false) String code){
        List<ContractProduct> list = new ArrayList<>();
        if(code==null && "".equals(code)) {
            PageVo<ContractProduct> result = new PageVo<>(list,list.size());
            return result;
        }
        EntityWrapper<ContractProduct> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("contract_code",code);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        list = contractProductService.selectList(entityWrapper);
        PageVo<ContractProduct> result = new PageVo<>(list,list.size());
        return result;
    }

    @RequestMapping(value = "contractProductAdd")
    @ResponseBody
    public MessageResult contractProductAdd(ContractProduct param){
        contractProductService.insert(param);
        return MessageResult.getSuccess("添加数据成功");
    }

    @RequestMapping(value = "contractProductEdit")
    @ResponseBody
    public MessageResult contractProductEdit(ContractProduct param){
        contractProductService.updateById(param);
        return MessageResult.getSuccess("修改数据成功") ;
    }

    @RequestMapping(value = "contractProductRemove")
    @ResponseBody
    public MessageResult contractProductRemove(@RequestParam String ids){
        EntityWrapper<ContractProduct> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("id",ids);
        if(ids==null || ids.equals("")){
            return MessageResult.getSuccess("数据删除失败，请先保存合同信息");
        }
        contractProductService.delete(entityWrapper);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "codeSelect")
    @ResponseBody
    public MessageResult codeSelect(String  code){
        EntityWrapper<Contract> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("code",code);
        Contract bean = contractService.selectOne(entityWrapper);
        if(bean==null){
            return MessageResult.getError("400","没有合同编号");
        }
        return MessageResult.getSuccess("合同编号已存在");
    }

    @RequestMapping(value = "save")
    @ResponseBody
    public CommonResult save(HttpServletRequest request, Contract param){
        User session = (User)request.getSession().getAttribute("loginUser");
        Userop userop = new Userop(new Date(),session.getUsername(),"合同添加",param.toString());
        Contract resut = contractService.save(param);
        useropService.save(userop);
        return CommonResult.success(resut,"合同添加成功");
    }

    @RequestMapping(value = "update")
    @ResponseBody
    public CommonResult update(HttpServletRequest request, Contract param){
        String[] temp = param.getSignman().split(",");
        if(temp.length>1){
            param.setSignman(temp[0]);
        }
        User session = (User)request.getSession().getAttribute("loginUser");
        Userop userop = new Userop(new Date(),session.getUsername(),"合同变更",param.toString());
        contractService.update(param);
        useropService.save(userop);
        return CommonResult.success(param,"合同修改成功");
    }

    @RequestMapping(value = "delete")
    @ResponseBody
    public MessageResult delete(HttpServletRequest request,@RequestParam Integer ids){
        User session = (User)request.getSession().getAttribute("loginUser");
        Userop userop = new Userop(new Date(),session.getUsername(),"合同删除",ids+":合同已删除");
        contractService.delete(ids);
        useropService.save(userop);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "remove")
    @ResponseBody
    public MessageResult deletes(HttpServletRequest request,@RequestParam String ids){
        User session = (User)request.getSession().getAttribute("loginUser");
        Userop userop = new Userop(new Date(),session.getUsername(),"合同删除",ids+":合同已删除");
        if(ids!=null && ids.equals("")){
            return MessageResult.getSuccess("数据删除失败，合同没有保存");
        }
        contractService.remove(ids);
        useropService.save(userop);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "fileup")
    @ResponseBody
    public MessageResult save(HttpServletRequest request,Contract param, @RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return MessageResult.getError("500","上传失败，请选择文件");
        }
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
        ServletContext application = request.getServletContext();
        String savePath = "C:\\picture\\";
        // 文件保存目录URL
        String saveUrl = request.getContextPath()+"/files/";
        // 定义允许上传的文件扩展名
        HashMap<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

        // 检查目录
        File uploadDir = new File(savePath);
        if (!uploadDir.isDirectory()) {
            return MessageResult.getError("500","上传目录不存在。");
        }
        // 检查目录写权限
        if (!uploadDir.canWrite()) {
            return MessageResult.getError("500","上传目录没有写权限。");
        }

        String dirName = getDirName(extMap,fileExt);
        // 创建文件夹
        savePath += dirName + "/";
        saveUrl += dirName + "/";
        File saveDirFile = new File(savePath);
        if (!saveDirFile.exists()) {
            saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String ymd = sdf.format(new Date());
        savePath += ymd + "/";
        saveUrl += ymd + "/";
        File dirFile = new File(savePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        // 检查扩展名

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        File uploadedFile = new File(savePath, newFileName);
        param.setFiles(saveUrl + newFileName);
        try {
            ByteStreams.copy(file.getInputStream(), new FileOutputStream(uploadedFile));
            contractService.update(param);
            User session = (User)request.getSession().getAttribute("loginUser");
            Userop userop = new Userop(new Date(),session.getUsername(),"合同附件添加",param.toString());
            useropService.save(userop);
            return MessageResult.getSuccess("添加附件成功");
        } catch (Exception e) {
            return MessageResult.getError("500","添加附件失败："+e.getMessage());
        }
    }

    private String getDirName(HashMap<String, String> map,String ext){
        for(String key:map.keySet()){
            String value = map.get(key);
            boolean status = value.contains(ext);
            if(status){
                return key;
            }
        }
        return "file";
    }

    @RequestMapping(value = "sendItemList")
    @ResponseBody
    public PageVo<Sendmk> sendItemList(Pagination<Sendmk> pagination,@RequestParam(required = false) String code){
        List<Sendmk> list = new ArrayList<>();
        if(code==null && "".equals(code)) {
            PageVo<Sendmk> result = new PageVo<>(list,list.size());
            return result;
        }
        EntityWrapper<Sendmk> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ctcode",code);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        list = sendmkService.selectList(entityWrapper);
        PageVo<Sendmk> result = new PageVo<>(list,list.size());
        return result;
    }

    @RequestMapping(value = "sendmkAdd")
    @ResponseBody
    public MessageResult sendmkAdd(HttpServletRequest request,Sendmk param){
        User session = (User)request.getSession().getAttribute("loginUser");
        param.setOpid(session.getId());
        param.setOpname(session.getUsername());
        sendmkService.insert(param);
        //更新合同状态
        updateContract(param.getCtcode());
        return MessageResult.getSuccess("添加数据成功");
    }

    @RequestMapping(value = "sendmkEdit")
    @ResponseBody
    public MessageResult sendmkEdit(Sendmk param){
        sendmkService.updateById(param);
        return MessageResult.getSuccess("修改数据成功");
    }

    @RequestMapping(value = "sendmkRemove")
    @ResponseBody
    public MessageResult sendmkRemove(@RequestParam String ids){
        EntityWrapper<Sendmk> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("id",ids);
        if(ids!=null && ids.equals("")){
            return MessageResult.getSuccess("数据删除失败，合同没有保存");
        }
        sendmkService.delete(entityWrapper);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "paymentItemList")
    @ResponseBody
    public PageVo<Payment> paymentItemList(Pagination<Payment> pagination,@RequestParam(required = false) String code){
        List<Payment> list = new ArrayList<>();
        if(code==null && "".equals(code)) {
            PageVo<Payment> result = new PageVo<>(list,list.size());
            return result;
        }
        EntityWrapper<Payment> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ctcode",code);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        list = paymentService.selectList(entityWrapper);
        PageVo<Payment> result = new PageVo<>(list,list.size());
        return result;
    }

    @RequestMapping(value = "paymentAdd")
    @ResponseBody
    public MessageResult paymentAdd(HttpServletRequest request,Payment param){
        User session = (User)request.getSession().getAttribute("loginUser");
        if(session==null)
            return MessageResult.getError("500","请重新登录！");
        param.setOpid(session.getId());
        param.setOpname(session.getUsername());
        //处理到货款
        Contract bean = contractService.selectByCode(param.getCtcode());
        bean.setPayment(bean.getPayment().add(param.getReceive()));
        bean.setLastpay(bean.getTotal().subtract(bean.getPayment()));
        //bean.setLastpay(bean.getReceivables().subtract(bean.getPayment()));
        bean.setLastpaytime(param.getCrtime());
        bean.setStatus("合同执行");
        contractService.update(bean);
        paymentService.insert(param);
        Userop userop = new Userop(new Date(),session.getUsername(),"增加到款信息",param.toString());
        useropService.save(userop);
        return MessageResult.getSuccess("添加数据成功");
    }

    @RequestMapping(value = "paymentEdit")
    @ResponseBody
    public MessageResult paymentEdit(HttpServletRequest request,Payment param){
        User session = (User)request.getSession().getAttribute("loginUser");
        if(session==null)
            return MessageResult.getError("500","请重新登录！");
        Payment old = paymentService.selectById(param.getId());
        //处理修改到货款
        Contract bean  = contractService.selectByCode(param.getCtcode());
        bean.setPayment(bean.getPayment().subtract(old.getReceive()).add(param.getReceive()));
        bean.setLastpay(bean.getReceivables().subtract(bean.getPayment()));
        bean.setLastpaytime(param.getCrtime());
        contractService.update(bean);
        paymentService.updateById(param);
        Userop userop = new Userop(new Date(),session.getUsername(),"修改到款信息-修改到款金额","old:"+old.toString()+"now:"+param.toString());
        useropService.save(userop);
        return MessageResult.getSuccess("修改数据成功");
    }

    @RequestMapping(value = "paymentRemove")
    @ResponseBody
    public MessageResult paymentRemove(HttpServletRequest request,@RequestParam String ids){
        User session = (User)request.getSession().getAttribute("loginUser");
        if(session==null)
            return MessageResult.getError("500","请重新登录！");
        EntityWrapper<Payment> entityWrapper = new EntityWrapper<>();
        if(ids==null || "".equals(ids.trim())){
            return MessageResult.getError("500","数据删除错误，请先保存合同！");
        }
        entityWrapper.in("id",ids);
        String[] idsString = ids.split(",");
        for(String id:idsString){
            if(id!=null && !id.equals("")) {
                //处理删除到货款
                Payment old = paymentService.selectById(Integer.parseInt(id));
                Contract bean = contractService.selectByCode(old.getCtcode());
                bean.setPayment(bean.getPayment().subtract(old.getReceive()));
                bean.setLastpay(bean.getReceivables().subtract(bean.getPayment()));
                contractService.update(bean);
                Userop userop = new Userop(new Date(),session.getUsername(),"删除到款信息-修改到款金额","old"+old.toString());
                useropService.save(userop);
            }
        }
        Userop userop = new Userop(new Date(),session.getUsername(),"删除到款信息",ids);
        useropService.save(userop);
        paymentService.delete(entityWrapper);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "billsItemList")
    @ResponseBody
    public PageVo<Bills> billsItemList(Pagination<Bills> pagination,@RequestParam(required = false) String code){
        List<Bills> list = new ArrayList<>();
        if(code==null && "".equals(code)) {
            PageVo<Bills> result = new PageVo<>(list,list.size());
            return result;
        }
        EntityWrapper<Bills> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ctcode",code);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        list = billsService.selectList(entityWrapper);
        PageVo<Bills> result = new PageVo<>(list,list.size());
        return result;
    }

    @RequestMapping(value = "billsAdd")
    @ResponseBody
    @Transactional
    public MessageResult billsAdd(HttpServletRequest request,Bills param){
        User session = (User)request.getSession().getAttribute("loginUser");
        param.setOpid(session.getId());
        param.setOpname(session.getUsername());
        //处理到货款
        Contract bean = contractService.selectByCode(param.getCtcode());
        BigDecimal totalBill = bean.getTotalbill();
        if(totalBill==null ){
            totalBill = new BigDecimal(0);
        }
        bean.setTotalbill(new BigDecimal(totalBill.doubleValue()+param.getReceive().doubleValue()));
        bean.setStatus("合同执行");
        contractService.update(bean);
        billsService.insert(param);
        return MessageResult.getSuccess("添加数据成功");
    }

    @RequestMapping(value = "billsEdit")
    @ResponseBody
    @Transactional
    public MessageResult billsEdit(Bills param){
        Bills old = billsService.selectById(param.getId());
        //处理到货款
        Contract bean = contractService.selectByCode(param.getCtcode());
        BigDecimal totalBill = bean.getTotalbill();
        if(totalBill==null ){
            totalBill = new BigDecimal(0);
        }
        bean.setTotalbill(new BigDecimal(totalBill.doubleValue()-old.getReceive().doubleValue()+param.getReceive().doubleValue()));
        contractService.update(bean);
        billsService.updateById(param);
        return MessageResult.getSuccess("修改数据成功");
    }

    @RequestMapping(value = "billsRemove")
    @ResponseBody
    @Transactional
    public MessageResult billsRemove(@RequestParam String ids){
        EntityWrapper<Bills> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("id",ids);
        String[] idsString = ids.split(",");
        for(String id:idsString){
            if(id!=null && !id.equals("")) {
                //处理删除到货款
                Bills old = billsService.selectById(Integer.parseInt(id));
                Contract bean = contractService.selectByCode(old.getCtcode());
                bean.setTotalbill(new BigDecimal(bean.getTotalbill().doubleValue()-old.getReceive().doubleValue()));
                contractService.update(bean);
            }
        }
        billsService.delete(entityWrapper);
        return MessageResult.getSuccess("数据已删除");
    }

    @RequestMapping(value = "cardItemList")
    @ResponseBody
    public PageVo<Bdcard> cardItemList(Pagination<Bdcard> pagination,@RequestParam(required = false) String code){
        List<Bdcard> list = new ArrayList<>();
        if(code==null && "".equals(code)) {
            PageVo<Bdcard> result = new PageVo<>(list,list.size());
            return result;
        }
        EntityWrapper<Bdcard> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ctcode",code);
        if(pagination.getOrder()!=null) {
            if (pagination.getOrder().toLowerCase().equals("asc")){
                entityWrapper.orderBy(pagination.getSort(), true);
            }else{
                entityWrapper.orderBy(pagination.getSort(), false);
            }
        }
        list = bdcardService.selectList(entityWrapper);
        PageVo<Bdcard> result = new PageVo<>(list,list.size());
        return result;
    }

    @RequestMapping(value = "cardAdd")
    @ResponseBody
    public MessageResult cardAdd(HttpServletRequest request,Bdcard param){
        bdcardService.insert(param);
        //更新合同状态
        updateContract(param.getCtcode());
        updateContractCard(param.getCtcode());
        return MessageResult.getSuccess("添加数据成功");
    }

    /**
     * 更新合同状态
     * @param code   合同编号
     */
    private void updateContract(String code){
        EntityWrapper<Contract> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("code", code);
        Contract bean = new Contract();
        bean.setStatus("合同执行");
        contractService.update(bean,entityWrapper);
    }

    /**
     * 添加分理信息自动更新是否发卡状态
     * @param code   合同编号
     */
    private void updateContractCard(String code){
        EntityWrapper<Contract> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("code", code);
        Contract bean = new Contract();
        bean.setCardtype("已发卡");
        contractService.update(bean,entityWrapper);
    }

    @RequestMapping(value = "cardEdit")
    @ResponseBody
    public MessageResult cardEdit(Bdcard param){
        bdcardService.updateById(param);
        return MessageResult.getSuccess("修改数据成功");
    }

    @RequestMapping(value = "cardRemove")
    @ResponseBody
    public MessageResult cardRemove(@RequestParam String ids){
        EntityWrapper<Bdcard> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("id",ids);
        if(ids!=null && ids.equals("")){
            return MessageResult.getSuccess("数据删除失败，合同没有保存");
        }
        bdcardService.delete(entityWrapper);
        return MessageResult.getSuccess("数据已删除");
    }

    /**
     * 纠错用的
     * @return
     */
    @RequestMapping(value = "testItemList")
    @ResponseBody
    public PageVo<Bdcard> testItemList(){
        List<Bdcard> list = new ArrayList<>();
        PageVo<Bdcard> result = new PageVo<>(list,list.size());
        return result;
    }

    @RequestMapping(value = "readindex")
    public String readindex(){
        return "contract/readindex";
    }

    @RequestMapping(value = "readform")
    public String readform(ModelMap map, @RequestParam int id){
        Contract bean = contractService.selectById(id);
        ContractVo result = new ContractVo();
        BeanUtils.copyProperties(bean,result);
        if(bean.getServiceDate()!=null && !bean.getServiceDate().equals(""))
            result.setServiceDateValue(DateUtil.format(bean.getServiceDate(),"yyyy-MM-dd"));
        if(bean.getCrtime()!=null && !bean.getCrtime().equals(""))
            result.setCrtimeValue(DateUtil.format(bean.getCrtime(),"yyyy-MM-dd"));
        if(bean.getLastpaytime()!=null && !bean.getLastpaytime().equals(""))
            result.setLastpaytimeValue(DateUtil.format(bean.getLastpaytime(),"yyyy-MM-dd"));

        map.addAttribute("bean",result);
        return "contract/readform";
    }

    @RequestMapping("paymentform")
    public String paymentform(ModelMap map, @RequestParam int id){
        Contract bean = contractService.selectById(id);
        ContractVo result = new ContractVo();
        BeanUtils.copyProperties(bean,result);
        if(bean.getServiceDate()!=null && !bean.getServiceDate().equals(""))
            result.setServiceDateValue(DateUtil.format(bean.getServiceDate(),"yyyy-MM-dd"));
        if(bean.getCrtime()!=null && !bean.getCrtime().equals(""))
            result.setCrtimeValue(DateUtil.format(bean.getCrtime(),"yyyy-MM-dd"));
        if(bean.getLastpaytime()!=null && !bean.getLastpaytime().equals(""))
            result.setLastpaytimeValue(DateUtil.format(bean.getLastpaytime(),"yyyy-MM-dd"));

        map.addAttribute("bean",result);
        return "contract/paymentform";
    }

    @RequestMapping("filish")
    @ResponseBody
    public MessageResult filish(HttpServletRequest request, String ids){
        User session = (User)request.getSession().getAttribute("loginUser");
        EntityWrapper<Contract> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("id", ids);
        Contract bean = new Contract();
        bean.setStatus("合同完成");
        contractService.update(bean,entityWrapper);
        Userop userop = new Userop(new Date(),session.getUsername(),"合同变更","合同ID={"+ids+"}");
        useropService.save(userop);
        return MessageResult.getSuccess("合同完成成功");
    }

    @RequestMapping("delall")
    @ResponseBody
    public MessageResult delAll(@RequestParam String code) {
        //删除合同信息
        EntityWrapper<Contract> contractEntityWrapper = new EntityWrapper<>();
        contractEntityWrapper.eq("code", code);
        contractService.delete(contractEntityWrapper);
        //级联删除子信息，合同产品信息
        EntityWrapper<ContractProduct> contractProductEntityWrapper = new EntityWrapper<>();
        contractProductEntityWrapper.eq("contract_code", code);
        contractProductService.delete(contractProductEntityWrapper);
        //到款信息
        EntityWrapper<Payment> paymentEntityWrapper = new EntityWrapper<>();
        paymentEntityWrapper.eq("ctcode", code);
        paymentService.delete(paymentEntityWrapper);
        //开票信息
        EntityWrapper<Bills> billsEntityWrapper  = new EntityWrapper<>();
        billsEntityWrapper.eq("ctcode", code);
        billsService.delete(billsEntityWrapper);
        //发货信息
        EntityWrapper<Sendmk> sendmkEntityWrapper = new EntityWrapper<>();
        sendmkEntityWrapper.eq("ctcode", code);
        sendmkService.delete(sendmkEntityWrapper);
        //北斗卡信息
        EntityWrapper<Bdcard> bdcardEntityWrapper = new EntityWrapper<>();
        bdcardEntityWrapper.eq("ctcode", code);
        bdcardService.delete(bdcardEntityWrapper);

        return MessageResult.getSuccess("合同删除成功");
    }

    @RequestMapping("getPayment")
    @ResponseBody
    public List<String> getPayment(){
        EntityWrapper<Contract> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("del",0);
        List<Contract> list = contractService.selectList(entityWrapper);
        List<String> strList = new ArrayList<>();
        for(Contract bean : list){
            if(bean.getPayment().compareTo(BigDecimal.ZERO) == 1){
                String temp = String.format("insert into bdth_payment(ctcode,ctname,receive,crtime,opid,opname,type) " +
                        "values('%s','%s',%.2f,'%s','%d','%s','%s')",
                        bean.getCode(),bean.getName(),bean.getPayment().doubleValue(),"2019-11-29",1,"bdthadmin","转账");
                strList.add(temp);
            }
        }
        return strList;
    }

    @RequestMapping("getDemoExcel")
    @ResponseBody
    public List<String> getDemoExcel(){
        EntityWrapper<Contract> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("del",0);
        List<Contract> list = contractService.selectList(entityWrapper);
        List<String> strList = new ArrayList<>();
        for(Contract bean : list){
            if(bean.getPayment().compareTo(BigDecimal.ZERO) == 1){
                String temp = String.format("%s %.2f",
                        bean.getCode(),bean.getTotal());
                strList.add(temp);
            }
        }
        return strList;
    }

    @RequestMapping(value = "demoListExcel")
    public void demoListExcel(HttpServletResponse response){
        EntityWrapper<Contract> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("del",0);
        List<Contract> list = contractService.selectList(entityWrapper);
        ExcelDataVo excelDataVo = new ExcelDataVo();
        excelDataVo.setName("项目信息");
        List<String> titles = new ArrayList();
        titles.add("项目编号");
        titles.add("项目总价");
        excelDataVo.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        for (int i=0;i<list.size();i++){
            Contract bean = list.get(i);
            List<Object> row = new ArrayList();
            row.add(bean.getCode());
            String temp = String.format("%.2f",bean.getTotal());
            row.add(temp);
            rows.add(row);
        }
        excelDataVo.setRows(rows);
        try{
            ExcelUtils.exportExcel(response,"项目信息",excelDataVo);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }

    /**
     * 合同台账首页
     * @return
     */
    @RequestMapping(value = "httzindex")
    public String httzindex(){
        return "contract/httzindex";
    }

    /**
     *查询合同台账列表
     */
    @RequestMapping(value = "httzlist")
    @ResponseBody
    public PageVo<ContractPlusVo> httzlist(HttpServletRequest request, Pagination<Contract> pagination){
        User session = (User)request.getSession().getAttribute("loginUser");
        EntityWrapper<UserContract> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("userid",session.getId());
        List<UserContract> userContractList = userContractService.selectList(entityWrapper);
        String contractIds = "";
        for(UserContract bean : userContractList){
            contractIds+=bean.getContractid()+",";
        }
        contractIds += "0";
        Map<String ,Object> query = new HashMap<>();
        query.put("contractIds",contractIds);
        Page<ContractPlusVo> items = contractService.listPlusPages(pagination, query);
        PageVo<ContractPlusVo> pageVo = new PageVo<>(items.getRecords(),items.getTotal());
        return pageVo;
    }
}

